package run.halo.app.service.impl;
import cn.binarywang.wx.miniapp.api.WxMaService;
import com.google.gson.JsonObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import run.halo.app.config.WxMaConfiguration;
import run.halo.app.model.vo.SecCheckVo;
import run.halo.app.service.SecCheckService;
import run.halo.app.utils.JsonUtils;

@Slf4j
@Service
public class SecCheckServiceImpl  implements  SecCheckService {

    String MSG_SEC_CHECK_URL = "https://api.weixin.qq.com/wxa/msg_sec_check";

    private boolean checkMessage(String msgString)  {
        try {
            JsonObject jsonObject = new JsonObject();
            jsonObject.addProperty("content", msgString);
            final WxMaService wxService = WxMaConfiguration.getAppService();
            String res=wxService.post(MSG_SEC_CHECK_URL, jsonObject.toString());
            log.info("内容安全检测："+res);
            SecCheckVo vo=JsonUtils.jsonToObject(res, SecCheckVo.class);
            if (res==null) {
                return false;
            }
            if (vo.getErrcode()==87014){
                return true;
            }
            return false;
        }
        catch (Exception e ){
            //内容含有违法违规内容 报异常
            return true;
        }
    }

    @Override
    public boolean checkMsg(String msg) {
        return checkMessage(msg);
    }

    @Override
    public boolean checkImg(String file) {
        try {
          final WxMaService wxService = WxMaConfiguration.getAppService();
          return wxService.getSecCheckService().checkImage(file);
        }
        catch (Exception e ){
            return false;
        }
    }
}
